/****************************************************************************
 *
 *  ALi (Zhuhai) Corporation, All Rights Reserved. 2010 Copyright (C)
 *
 *  File: Win_Chapter.c
 *
 *  Description: Mediaplayer chapter switch.
 *
 *  History:
 *  Date            Author  	Version       Comment
 *  ====            ======  	=======       =======
 *  1.  2010.8.25   Terry Wu 	0.1.000  initial for mediaplayer 2.0
 *
 ****************************************************************************/

#include <types.h>
#include <osal/osal.h>
#include <api/libc/printf.h>
#include <api/libc/string.h>
#include <api/libosd/osd_lib.h>
#include <api/libttx/lib_ttx.h>
#include <api/libsubt/lib_subt.h>
#include <api/libmp/mp_subtitle_api.h>
#include <api/libmp/media_player_api.h>

#include "copper_common/system_data.h"
#include "copper_common/com_api.h"

#include "osdobjs_def.h"
#include "win_com_menu_define.h"
#include "win_com_popup.h"
#include "menus_root.h"

#include "osd_config.h"
#include "string.id"
#include "images.id"

#include "win_subtitle.h"
#include "win_com.h"


/*******************Global Variable***********************/

#define CHAPTER_ITEM_NUMBER 30
#define VIDEO_SEARCH_DLYS 2
#define MP_TRICK_TIMEOUT    100// 4000 // 555
//  Gavim@20141014-----------
static ID		chapter_timer = OSAL_INVALID_ID;
#define PROGNAME_TIMER_NAME 	"winchapter"
//-------------------------------------

UINT16	Chapter_track_idx[CHAPTER_ITEM_NUMBER][5];   //list num
UINT16	Chapter_track_str[CHAPTER_ITEM_NUMBER][30];  //list content string

UINT16 * p_chapter_track_str[CHAPTER_ITEM_NUMBER];
UINT16 * p_chapter_track_idx[CHAPTER_ITEM_NUMBER];

LISTFIELD list_field_chapter[] = 
{
	{80,4,0,0,0,C_ALIGN_LEFT|C_ALIGN_VCENTER,FIELD_IS_TEXT,p_chapter_track_idx},
	{SUBTITLE_LS_W-80,0,0,0,0,C_ALIGN_LEFT|C_ALIGN_VCENTER,FIELD_IS_TEXT,p_chapter_track_str},
};    //every list has ID and content 



/************************Function Protocol*************************/
void PlayProc();
void win_com_set_idx_str2(UINT8 * idx, UINT16 * str,UINT8 len);
void win_com_set_idx_str(UINT16 idx, UINT16 * str, UINT16 len);
static VACTION chapter_con_keymap(POBJECT_HEAD obj, UINT32 key);
static PRESULT chapter_con_callback(POBJECT_HEAD pObj, VEVENT event, UINT32 param1, UINT32 param2);
static PRESULT chapter_list_callback(POBJECT_HEAD obj, VEVENT event, UINT32 param1, UINT32 param2);
static VACTION chapter_list_keymap(POBJECT_HEAD obj, UINT32 key);



/*******************************************************************************
*	Objects definition
*******************************************************************************/

extern CONTAINER	g_cnt_chapter;
extern TEXT_FIELD	g_txt_chapter;
extern LIST		g_ls_chapter;
extern SCROLL_BAR	g_sb_chapter;

CONTAINER    g_cnt_chapter={
	{	OT_CONTAINER,     //object type
		C_ATTR_ACTIVE,    // defined in form C_ATTR_XXX
		C_FONT_DEFAULT,   // defined in form C_FONT_XXX
		0,                // 0: for component without focus

		0,                //UINT8 bLeftID;
		0,                //UINT8 bRightID;
		0,                //UINT8 bUpID;
		0,                //UINT8 bDownID;

		{SUBTITLE_L, SUBTITLE_T, SUBTITLE_W, SUBTITLE_H},//OSD_RECT frame;
		{WSTL_WIN_SLIST_02_8BIT, WSTL_WIN_SLIST_02_8BIT, WSTL_WIN_SLIST_02_8BIT, WSTL_WIN_SLIST_02_8BIT},//COLOR_STYLE style;

		chapter_con_keymap,       //PFN_KEY_MAP pfnKeyMap;
		chapter_con_callback,     //PFN_CALLBACK pfnCallback;

		NULL,                     //POBJECT_HEAD pNext;
		NULL                      //POBJECT_HEAD pRoot;
	},
	(POBJECT_HEAD)&g_txt_chapter,
	1,                            //focus
	0
};

TEXT_FIELD	g_txt_chapter = {
	{	OT_TEXTFIELD,          //object type
		C_ATTR_ACTIVE,         // defined in form C_ATTR_XXX
		C_FONT_DEFAULT,        // defined in form C_FONT_XXX
		0,      			   // 0: for component without focus

		0,					  //UINT8 bLeftID;
		0,                    //UINT8 bRightID;
		0,                    //UINT8 bUpID;
		0,                    //UINT8 bDownID;

		{SUBTITLE_TXT_L, SUBTITLE_TXT_T, SUBTITLE_TXT_W, SUBTITLE_TXT_H},//OSD_RECT frame;
		{WSTL_MIXBACK_IDX_04_8BIT, WSTL_MIXBACK_IDX_04_8BIT, WSTL_MIXBACK_IDX_04_8BIT, 0},//COLOR_STYLE style;

		NULL,                //PFN_KEY_MAP pfnKeyMap;
		NULL,                //PFN_CALLBACK pfnCallback;

		(POBJECT_HEAD)&g_ls_chapter,      //POBJECT_HEAD pNext;
		(POBJECT_HEAD)&g_cnt_chapter,     //POBJECT_HEAD pRoot;
	},
	C_ALIGN_CENTER | C_ALIGN_VCENTER,     //UINT8 bAlign;
	0,         //UINT8 bX;
	0,         //UINT8 bY;
	RS_CHAPTER,  //UINT16 wStringID;  // string id
	NULL,                                  //UINT16* pString;   // unicode string pointer
};

#define LDEF_SET_LIST(root, varCon,nxtObj,l,t,w,h,field,numfield,page,bar,intervaly,keymap,callback)		\
	DEF_LIST(varCon,root,nxtObj,C_ATTR_ACTIVE,0, \
	1,1,1,1,1,l,t,w,h, LIST_SH_IDX,LIST_HL_IDX,LIST_SL_IDX,LIST_GRY_IDX,\
	keymap,callback,LIST_FULL_PAGE| LIST_PAGE_KEEP_CURITEM|LIST_GRID|LIST_SCROLL,\
	field,numfield,page,(SCROLL_BAR* )bar,intervaly,NULL,0/*cnt*/,0/*ntop*/,0/*nsel*/,0/*npos*/)

#define LDEF_LISTBAR(root,varScb,page,l,t,w,h)	\
	DEF_SCROLLBAR(varScb,root, NULL, C_ATTR_ACTIVE, 0, \
		0, 0, 0, 0, 0, l, t, w, h, LIST_BAR_SH_IDX, LIST_BAR_HL_IDX, LIST_BAR_SH_IDX, LIST_BAR_SH_IDX, \
		NULL, NULL, BAR_VERT_AUTO | SBAR_STYLE_RECT_STYLE, page, LIST_BAR_MID_THUMB_IDX, LIST_BAR_MID_RECT_IDX, \
		0, 10, w, h - 20, 100, 1)

LDEF_SET_LIST(&g_cnt_chapter,g_ls_chapter,&g_sb_chapter, \
				SUBTITLE_LS_L, SUBTITLE_LS_T, SUBTITLE_LS_W, SUBTITLE_LS_H,\
				list_field_chapter,2,SUBTITLE_LS_PAGE,&g_sb_chapter,0,\
				chapter_list_keymap,chapter_list_callback);
LDEF_LISTBAR(&g_cnt_chapter,g_sb_chapter,\
				SUBTITLE_LS_PAGE,SUBTITLE_SB_L, SUBTITLE_SB_T, SUBTITLE_SB_W, SUBTITLE_SB_H);



/*****************************************************
Interface : void GetListChapterInfo(UINT16 top);
Function  : set each item's display content of list
Author    : Wu Jianwen
Date      : 2010.8.25
Input     : top:first item of list
Output    : NONE
Return    : NONE
******************************************************/
//   Gavim@20141014 -----------
void chapter_timer_func(UINT unused)
{
	  CHENGYU_PRINTF(" ========chapter_timer_func========== \n");	
	api_stop_timer(&chapter_timer);
	ap_send_msg(CTRL_MSG_SUBTYPE_CMD_EXIT, 1, TRUE);	 

}
//-----------------------------------------

void GetListChapterInfo(INT16 top)
{
	UINT8 len = 0;
	UINT8 i = 0;
	INT32 hh,mm,ss;         //start time
	INT32 hh2,mm2,ss2;      //end time
	UINT8 arr_DataTemp[50];
	UINT8  back_saved;
	INT32 i_TotalChapter = 0;      //the total chapter of the video
	INT32 i_CurChapStartTime = 0;   //current chapter start time
	INT32 i_CurChapEndTime = 0;     //current chapter end time
	INT32 i_DestChapStartTime = 0;  //Dest chapter start time
	INT32 i_DestChapEndTime = 0;    //Dest chapter end time
	INT32 i_DestChapter = 0;        //dest chapter num
    INT32 i_CurChapter = 1;         //current chapter num
    INT32 i_ChapterChange = 0;
	DEC_CHAPTER_INFO t_ChapterInfo; //save chapter info of the stream
	

	MEMSET(&t_ChapterInfo,0,sizeof(DEC_CHAPTER_INFO));
	t_ChapterInfo.dst_chapter = -1;
	MpgFileGetChapterInfo(&t_ChapterInfo);   //get the current chapter info 
	i_CurChapter = t_ChapterInfo.cur_chapter;   //begin with chapter
	i_TotalChapter = t_ChapterInfo.nb_chapter;
			
	if(i_TotalChapter > 1)   //only chapter num > 1 can switch
	{
		if(top > i_TotalChapter)
		{
			top = 0;
			OSD_SetListCurPos(&g_ls_chapter,0);
			OSD_SetListTop(&g_ls_chapter,0);
		}
		i = 0;
		for(i = 0;i < CHAPTER_ITEM_NUMBER;i++)
		{
			i_ChapterChange = top + i;
			if(i_ChapterChange < i_TotalChapter)
			{
				i_DestChapter = i_ChapterChange;
				t_ChapterInfo.dst_chapter = i_DestChapter;
				MpgFileGetChapterInfo(&t_ChapterInfo);
				i_DestChapStartTime = t_ChapterInfo.dst_start_time / 1000;
				hh = i_DestChapStartTime / 3600;
				mm = (i_DestChapStartTime % 3600) / 60;
				ss = i_DestChapStartTime % 60;
				i_DestChapEndTime = t_ChapterInfo.dst_end_time / 1000;
				hh2 = i_DestChapEndTime / 3600;
				mm2 = (i_DestChapEndTime % 3600) / 60;
				ss2 = i_DestChapEndTime % 60;

				arr_DataTemp[0] = hh;
				arr_DataTemp[1] = mm;
				arr_DataTemp[2] = ss;
				arr_DataTemp[3] = hh2;
				arr_DataTemp[4] = mm2;
				arr_DataTemp[5] = ss2;
				win_com_set_idx_str2(arr_DataTemp, &Chapter_track_str[i][0],6);
				win_com_set_idx_str(top+i, Chapter_track_idx[i], 2);
			}		
			else
			{
				//memset(&Chapter_track_idx[i],0,40);
				break;
			}
		}
	}
	else
	{
		win_compopup_init(WIN_POPUP_TYPE_SMSG);
		win_compopup_set_frame(MSG_POPUP_LAYER_L, MSG_POPUP_LAYER_T, MSG_POPUP_LAYER_W, MSG_POPUP_LAYER_H);
        win_compopup_set_msg_ext("There is only one chapter!",NULL,0);
        win_compopup_open_ext(&back_saved);
        osal_task_sleep(1500);
        win_compopup_smsg_restoreback();
	}
}


/*****************************************************
Interface : void ListChapterInfoInit();
Function  : init chapter list
Author    : Wu Jianwen
Date      : 2010.8.25
Input     : NONE
Output    : NONE
Return    : NONE
******************************************************/
void ListChapterInfoInit()
{
	UINT16 top;
	UINT32 i_TotalChapter = 0;      //the total chapter of the video
	INT32 i_DestChapter = 0;        //dest chapter num
    INT32 i_CurChapter = 1;         //current chapter num
	DEC_CHAPTER_INFO t_ChapterInfo; //save chapter info of the stream

	MEMSET(&t_ChapterInfo,0,sizeof(DEC_CHAPTER_INFO));
	t_ChapterInfo.dst_chapter = -1;
	MpgFileGetChapterInfo(&t_ChapterInfo);   //get the current chapter info 
	i_CurChapter = t_ChapterInfo.cur_chapter;   //begin with chapter
	i_TotalChapter = t_ChapterInfo.nb_chapter;

	OSD_SetListCount(&g_ls_chapter, i_TotalChapter);
	OSD_SetListCurPos(&g_ls_chapter, i_CurChapter);
	OSD_SetListTop(&g_ls_chapter, i_CurChapter);
	OSD_SetListVerScrollBar(&g_ls_chapter, &g_sb_chapter);
	
	top = OSD_GetListTopPoint(&g_ls_chapter);
	GetListChapterInfo(top);
}



/*****************************************************
Interface : VACTION chapter_con_keymap(POBJECT_HEAD obj, UINT32 key);
Function  : keymap of chapter container
Author    : Wu Jianwen
Date      : 2010.8.25
Input     : obj:container; key:v_Key of press button
Output    : NONE
Return    : NONE
******************************************************/
VACTION chapter_con_keymap(POBJECT_HEAD obj, UINT32 key)
{
	VACTION act;
	
	switch(key)
	{
		case V_KEY_EXIT:
		case V_KEY_MENU:
		case V_KEY_SUBTITLE:
			act = VACT_CLOSE;
			break;		
		case V_KEY_ENTER:
			act = VACT_ENTER;
			break;		
		default:	
			act = OSD_ContainerKeyMap(obj,key);
	}

	return act;
}


/*****************************************************
Interface : static PRESULT chapter_con_callback(POBJECT_HEAD pObj, VEVENT event, UINT32 param1, UINT32 param2);
Function  : callback of chapter container
Author    : Wu Jianwen
Date      : 2010.8.25
Input     : 
Output    : NONE
Return    : 
******************************************************/
static PRESULT chapter_con_callback(POBJECT_HEAD pObj, VEVENT event, UINT32 param1, UINT32 param2)
{
	PRESULT ret = PROC_PASS;
	UINT8 i;
	UINT16 wait_time = 0;
	UINT8 unact = 0;
	INT32 i_DestChapter = 0;        //dest chapter num
	INT32 i_DestChapStartTime;
	DEC_CHAPTER_INFO t_ChapterInfo;    //save chapter info of the stream

	switch(event)
	{
	case EVN_MSG_GOT:
		if(param1 ==  CTRL_MSG_SUBTYPE_CMD_EXIT)
		{
			ret = PROC_LEAVE;
		}
#ifdef USB_MP_SUPPORT
		else if(param1 == CTRL_MSG_SUBTYPE_STATUS_VIDEO_OVER)
		{
			ret = PROC_LEAVE;
			ap_send_msg(CTRL_MSG_SUBTYPE_STATUS_VIDEO_OVER,0,TRUE);
		}
#endif
		break;
	case EVN_POST_OPEN:
		    // Gavim@20141014-------------------
		    CHENGYU_PRINTF(" ========EVN_POST_OPEN========== \n");	
			SYSTEM_DATA* sys_data;
			sys_data = sys_data_get();    	
			UINT32 	timeout = sys_data->osd_set.time_out;
			timeout = timeout*1000;
			chapter_timer = api_start_timer(PROGNAME_TIMER_NAME, timeout ,chapter_timer_func);
	         //---------------------------------------------       	
			break;	
	case EVN_PRE_OPEN:
        api_set_deo_layer(0);
        api_inc_wnd_count();

		for(i=0;i<CHAPTER_ITEM_NUMBER;i++)
		{
			p_chapter_track_str[i]=Chapter_track_str[i];
			p_chapter_track_idx[i]=Chapter_track_idx[i];
		}
		ListChapterInfoInit();
		break;		
		
	case EVN_UNKNOWN_ACTION:
		unact = (VACTION)(param1>>16);
		if(VACT_ENTER == unact)
		{
			i_DestChapter = OSD_GetListCurPoint(&g_ls_chapter);  //get current chapter
			t_ChapterInfo.dst_chapter = i_DestChapter;
			MpgFileGetChapterInfo(&t_ChapterInfo);
			//i_DestChapStartTime = t_ChapterInfo.dst_start_time/1000;   //second
			i_DestChapStartTime = t_ChapterInfo.dst_start_time;   //ms
			if(t_ChapterInfo.dst_start_time > t_ChapterInfo.cur_start_time)  
			{
				//mpg_cmd_search_proc((DWORD)i_DestChapStartTime);
				mpg_cmd_search_ms_proc((DWORD)i_DestChapStartTime);
				while ((i_DestChapStartTime > MPGFileDecoderGetPlayTime()) && (wait_time < MP_TRICK_TIMEOUT))
				{
					osal_task_sleep(2);
					wait_time++;
				}
			}
			else                  //chapter18 to chapter1          
			{
				//mpg_cmd_search_proc((DWORD)i_DestChapStartTime);
				mpg_cmd_search_ms_proc((DWORD)i_DestChapStartTime);
				while ((i_DestChapStartTime + VIDEO_SEARCH_DLYS < MPGFileDecoderGetPlayTime()) && (wait_time < MP_TRICK_TIMEOUT))
				{
					osal_task_sleep(2);
					wait_time++;
				}
			}
			
			PlayProc();
			OSD_ObjClose(pObj,C_CLOSE_CLRBACK_FLG);
			return PROC_LEAVE;		
		}
		break;
		
	case EVN_PRE_CLOSE:
		ret = PROC_PASS;
        break;

	case EVN_POST_CLOSE:
        api_set_deo_layer(1);
        api_dec_wnd_count();
        break;
	default:
		break;
	}

	return ret;
}



/*****************************************************
Interface : static VACTION chapter_list_keymap(POBJECT_HEAD obj, UINT32 key);
Function  : keymap of chapter list
Author    : Wu Jianwen
Date      : 2010.8.25
Input     : obj:container; key:v_Key of press button
Output    : NONE
Return    : NONE
******************************************************/
static VACTION chapter_list_keymap(POBJECT_HEAD obj, UINT32 key)
{
	VACTION	act = VACT_PASS;

	switch(key)
	{
		case V_KEY_LEFT:
  			act = VACT_CURSOR_LEFT;
  			break;
  		case V_KEY_RIGHT:
  			act = VACT_CURSOR_RIGHT;
  			break;
		case V_KEY_ENTER:
			act = VACT_ENTER;
			break;
		default:
			act = OSD_ListKeyMap(obj, key);
	}
	
	return act;
}


/*****************************************************
Interface : static PRESULT chapter_list_callback(POBJECT_HEAD obj, VEVENT event, UINT32 param1, UINT32 param2);
Function  : callback of chapter list
Author    : Wu Jianwen
Date      : 2010.8.25
Input     : 
Output    : NONE
Return    : 
******************************************************/
static PRESULT chapter_list_callback(POBJECT_HEAD obj, VEVENT event, UINT32 param1, UINT32 param2)
{
	UINT16 top, cnt, pos;
	UINT8 unact;
	PRESULT ret = PROC_PASS;

	switch(event)
	{
		case EVN_PRE_DRAW:			
			top= OSD_GetListTopPoint(&g_ls_chapter);
			GetListChapterInfo(top);		
			break;
			
		case EVN_REQUEST_DATA:
			top = (UINT16)param2;
			GetListChapterInfo(top);
			break;
		default:
			PRINTF("do nothing \n");
	}
	
	return ret;
}


void win_com_set_idx_str2(UINT8 * idx, UINT16 * str,UINT8 len)
{
	char tmp[20];
	char fmt[20];
	
	sprintf(tmp, "%d:%d:%d ~ %d:%d:%d", *idx,*(idx+1),*(idx+2),*(idx+3),*(idx+4),*(idx+5));
	ComAscStr2Uni(tmp, str);
}






